package mi.payment.ui.query;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import mi.payment.R;
import mi.payment.adapter.TransactionQueryAdapter;
import mi.payment.db.dao.PayDetail;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.CollectionUtil;
import mi.payment.utils.OrderJudgmentUtil;
import mi.payment.utils.ScreenUtil;


/**
 * 交易查询页面
 */
public class TransactionQueryActivity extends ParentActivity {

    private View searchLay;
    private View bottomLay;
    private RadioButton rdoCollect;
    private RadioButton rdoRefund;
    private View indicator;
    private ListView listView;
    private View noResult;
    private View goTop;
    private TextView tv_title;

    private TransactionQueryAdapter adapter;
    private List<PayDetail> collectList = new ArrayList<>();    // 收款记录
    private List<PayDetail> refundList = new ArrayList<>();     // 退款记录
    //是否过滤异常订单
    private boolean isFilterOrder = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_query);
        isFilterOrder = getIntent().getBooleanExtra("IS_FILTER_ORDER", false);
        initView();
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorBar));
        }

        findViewById(R.id.ic_back).setOnClickListener(this);
        findViewById(R.id.tv_trans_summary).setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);
        if (isFilterOrder) {
            tv_title.setText(getString(R.string.trans_exception_query));
        } else {
            tv_title.setText(getString(R.string.transaction_query));
        }

        searchLay = findViewById(R.id.search_lay);
        searchLay.setOnClickListener(this);
        bottomLay = findViewById(R.id.bottom_lay);
        RadioGroup queryGroup = (RadioGroup) findViewById(R.id.query_group);
        queryGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                adapter.setData(checkedId == R.id.rdo_collect ? collectList : refundList);
                refreshViewVisibility();
                showTabSwitchAnim();
            }

        });
        rdoCollect = (RadioButton) findViewById(R.id.rdo_collect);
        rdoCollect.setOnClickListener(this);
        rdoRefund = (RadioButton) findViewById(R.id.rdo_refund);
        rdoRefund.setOnClickListener(this);
        indicator = findViewById(R.id.indicate_view);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) indicator.getLayoutParams();
        params.width = ScreenUtil.getScreenW() / 2;
        indicator.setLayoutParams(params);
        adapter = new TransactionQueryAdapter(this);
        listView = (ListView) findViewById(R.id.list_view);
        View view = new View(this);
        ListView.LayoutParams vParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(10));
        view.setLayoutParams(vParams);
        view.setClickable(true);
        listView.addHeaderView(view);
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    int firstVisiblePosition = listView.getFirstVisiblePosition();
                    View firstView = listView.getChildAt(0);
                    if (firstVisiblePosition == 0 && firstView.getTop() == 0) {
                        // 列表滚到顶部
                        goTop.setVisibility(View.GONE);
                    } else {
                        goTop.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }

        });
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(parent.getContext(), TransactionDetailActivity.class);
                intent.putExtra(TransactionDetailActivity.TRANSACTION_DETAIL, (PayDetail) parent.getAdapter().getItem(position));
                startActivity(intent);
            }

        });
        noResult = findViewById(R.id.tv_no_result);
        goTop = findViewById(R.id.tv_go_top);
        goTop.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenData();
        refreshViewVisibility();
        updateIndicatorView();
    }

    private void setScreenData() {
        // 收款列表
        collectList.clear();
        collectList.addAll(mPayDetailModel.queryAllCollectMoneyRecords(isFilterOrder));
        Collections.sort(collectList, new Comparator<PayDetail>() {

            @Override
            public int compare(PayDetail lhs, PayDetail rhs) {
                return compareInner(lhs, rhs);
            }

        });

        // 退款列表
        refundList.clear();
        refundList.addAll(mPayDetailModel.queryAllRefundRecords(isFilterOrder));
        Collections.sort(refundList, new Comparator<PayDetail>() {

            @Override
            public int compare(PayDetail lhs, PayDetail rhs) {
                return compareInner(lhs, rhs);
            }

        });

        if (rdoCollect.isChecked()) {
            adapter.setData(collectList);
        } else if (rdoRefund.isChecked()) {
            adapter.setData(refundList);
        }
    }

    private int compareInner(PayDetail lhs, PayDetail rhs) {
        //+ 李少文；2017.12.18; 若订单需要冲正且未未冲正，置顶处理
        boolean lUnknown = isTopOrder(lhs);
        boolean rUnknown = isTopOrder(rhs);
        //+ 李少文；2017.12.18; 若订单需要冲正且未未冲正，置顶处理
        if (lUnknown && !rUnknown) {
            return -1;
        } else if (!lUnknown && rUnknown) {
            return 1;
        }
        return 0;
    }

    /*判断订单是否为置顶订单（不明订单，未冲正订单）*/
    private boolean isTopOrder(PayDetail payDetail) {
        boolean result = false;
        if (payDetail.transPlatform != 0) {
            // 扫码交易，先去查询是否是不明订单
            result = OrderJudgmentUtil.isQRUnknownOrder(payDetail);
        }
        if (payDetail.isNeedReversal && !payDetail.isReversal) {
            // 需要冲正且未冲正过的订单
            result = true;
        }
        return result;
    }

    private void refreshViewVisibility() {
        rdoCollect.setText(String.format(Locale.getDefault(), "%s(%d)", getString(R.string.collect_money), collectList.size()));
        rdoRefund.setText(String.format(Locale.getDefault(), "%s(%d)", getString(R.string.refund), refundList.size()));
        listView.setVisibility(View.VISIBLE);
        noResult.setVisibility(View.GONE);
        goTop.setVisibility(View.GONE);
        if (CollectionUtil.isEmpty(adapter.getData())) {
            listView.setVisibility(View.GONE);
            noResult.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新indicatorView的宽度和位置
     */
    private void updateIndicatorView() {
        // 更新indicateView的宽度
        indicator.clearAnimation();
        TextPaint paint = rdoCollect.getPaint();
        int rdoViewWidth = ScreenUtil.getScreenW() / 2;
        int txtSize1 = (int) (paint.measureText(rdoCollect.getText().toString()) + 0.5f);
        int txtSize2 = (int) (paint.measureText(rdoRefund.getText().toString()) + 0.5f);
        int width = Math.max(txtSize1, txtSize2) + ScreenUtil.dp2px(10); // indicatorView宽度,文字左右留出10的间距
        int transFrom = (rdoViewWidth - width) / 2;
        int transTo = rdoViewWidth + (rdoViewWidth - width) / 2;
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) indicator.getLayoutParams();
        params.width = width;
        indicator.setLayoutParams(params);
        if (rdoCollect.isChecked()) {
            indicator.setTranslationX(transFrom);
        } else if (rdoRefund.isChecked()) {
            indicator.setTranslationX(transTo);
        }
        rdoCollect.setTag(transFrom);
        rdoRefund.setTag(transTo);
    }

    /**
     * tab切换动画
     */
    private void showTabSwitchAnim() {
        int fromXDelta = 0;
        int toXDelta = 0;
        if (rdoCollect.isChecked()) {
            fromXDelta = (int) rdoRefund.getTag();
            toXDelta = (int) rdoCollect.getTag();
        } else if (rdoRefund.isChecked()) {
            fromXDelta = (int) rdoCollect.getTag();
            toXDelta = (int) rdoRefund.getTag();
        }
        ObjectAnimator animator = ObjectAnimator.ofFloat(indicator, "translationX", fromXDelta, toXDelta);
        animator.setDuration(200);
        animator.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ic_back:
                finish();
                break;
            case R.id.tv_trans_summary:
                openActivity(TransactionSummaryActivity.class);
                break;
            case R.id.search_lay:
                openActivity(TransactionSearchActivity.class);
                break;
            case R.id.tv_go_top:
                listView.setSelection(0);
                goTop.setVisibility(View.GONE);
                break;
        }
    }

    private int downY = 0;
    private int listViewTop = 0; // ListView的Y值
    private int searchLayHeight; // searchView的高度
    private boolean animShowing; // 动画是否正在显示

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            downY = (int) (event.getRawY() + 0.5f);
            listViewTop = getViewRawY(listView);
            searchLayHeight = searchLay.getHeight() + ((MarginLayoutParams) searchLay.getLayoutParams()).bottomMargin;
        } else if (event.getAction() == MotionEvent.ACTION_MOVE && !animShowing) {
            if (downY >= listViewTop && downY <= listViewTop + listView.getHeight()) {
                // 手指点在ListView上
                int currentY = (int) (event.getRawY() + 0.5f);
                int distance = currentY - downY; // 滑动的距离
                if (Math.abs(distance) >= ViewConfiguration.get(this).getScaledTouchSlop()) {
                    // 发生滑动事件
                    int y1 = getViewRawY(searchLay);
                    int y2 = getViewRawY(bottomLay);
                    if (distance < 0 && y1 < y2) {
                        // 向上滑动
                        animShowing = true;
                        showSlideAnim(true);
                    } else if (distance > 0 && y1 == y2) {
                        // 向下滑动
                        animShowing = true;
                        showSlideAnim(false);
                    }
                }
            }
        }
        return animShowing || super.dispatchTouchEvent(event);
    }

    private void showSlideAnim(final boolean upSlide) {
        final MarginLayoutParams params = (MarginLayoutParams) bottomLay.getLayoutParams();
        ValueAnimator anim = ValueAnimator.ofInt(0, searchLayHeight);
        anim.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (Integer) animation.getAnimatedValue();
                params.topMargin = upSlide ? -value : -searchLayHeight + value;
                bottomLay.setLayoutParams(params);
            }

        });
        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                animShowing = false;
            }

        });
        anim.setDuration(200);
        anim.start();
    }

    private int getViewRawY(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return location[1];
    }

}
